package com.lms.web;

import com.lms.mapper.UserDAO;
import com.lms.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "RegisterServlet", value = "/Register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        获取请求参数:用户名、密码和邮箱
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
//        验证用户名、邮箱和密码
        boolean isRegister = false;
        if (username != null && password != null && email != null) {
            User user = new User();
            user.setUserName(username);
            user.setPassword(password);
            user.setEmail(email);
            if (user.isValid()) {//格式正确则进行注册
                UserDAO userDAO = new UserDAO();
                isRegister = userDAO.register(user);
            } else {//格式错误
                req.setAttribute("error", "Invalid username, password or email format.");
            }
        } else {
            //提交的表单没有对应的参数
            req.setAttribute("error", "Invalid username, password or email format.");
        }

        if (isRegister) {
//        注册成功：跳转到登录界面
            resp.sendRedirect("login.jsp");
        } else {
//        注册失败：提示信息，返回登录页面
            req.getRequestDispatcher("register.jsp").forward(req, resp);  // Show register form again with error
        }

    }

}
